<template>
  <div class="sales-template-container">
    <van-loading type="spinner" v-if="isLoading" />
    <div v-else>
      <van-tabs v-model:active="active" sticky v-if="tabTitles.length > 1">
        <van-tab :title="name" v-for="(name, index) in tabTitles">
          <questionView :questionContent="questionContent(index)" />
        </van-tab>
      </van-tabs>
      <questionView :questionContent="questionContent(0)" v-else />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useSalesTemplateStore } from "@/store";
import { useRoute } from "vue-router";
import questionView from "./questionView.vue";

const route = useRoute();
const store = useSalesTemplateStore();
const active = ref(0);
const isLoading = ref(true);

onMounted(() => {
  initData();
});

async function initData() {
  const { token, isTest, confId } = route.query;
  console.log("initData :>> ", route.query);
  store.setConfId(confId);
  if (isTest) {
    setToken(
      "Bearer2 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzaW1wbGVMb2dpbiI6dHJ1ZSwiaXNzIjoib2N0IiwibmFtZSI6IuacseW6huelpSIsImlkIjoiZjBmZTZmYmQtYzdkMS00NTllLWJkMDYtODczZDA1ZGY1OWZjIiwib3JnSWQiOiIyNDJiMjU1YS1hNWE4LTQ4MGMtYTI1MS0zOWNhZTAyMGVhNjAifQ.JIX-xDVThCQwGqKo_U-pRgMPqmIhkglxchCJf5o8B1I"
    );
  }
  if (token && token.length > 0) {
    setToken(token);
  }
  isLoading.value = true;
  console.log("initData :>> ", store);
  await store.getGoodsCategoryAction();
  isLoading.value = false;
}

function questionContent(index) {
  console.log("questionContent 1 :>> ", templates.value, index);
  console.log("questionContent 2 :>> ", goodsQuestions.value, index);
  if (dataType.value === 1) {
    return templates.value[index];
  }
  if (dataType.value === 2) {
    return goodsQuestions.value[index];
  }
  return [];
}

const templates = computed(() => {
  return store.templates;
});

const goodsQuestions = computed(() => {
  return store.goodsQuestions;
});

const dataType = computed(() => {
  if (templates.value) return 1;
  if (goodsQuestions.value) return 2;
  return 0;
});

const tabTitles = computed(() => {
  if (dataType.value === 1) {
    return templates.value.map((v) => {
      return v.categoryName;
    });
  }
  if (dataType.value === 2) {
    return goodsQuestions.value.map((v) => {
      return v.title;
    });
  }
  return [];
});
</script>

<style lang="less" scoped>
.sales-template-container {
  display: flex;
  flex-direction: column;
}
</style>
